import { createStore } from 'vuex';

// localstorage里必须存json类型的数据
const setLocalCartList = (state) => {
  const { cartList } = state;
  const cartListString = JSON.stringify(cartList);
  localStorage.cartList = cartListString;
};

const getLocalCartList = () => {
  try {
    //持久化存储
    return JSON.parse(localStorage.cartList);
  } catch (error) {
    return {};
  }
};

export default createStore({
  state: {
    // 商铺id: {
    // 商铺名称: ''
    // 商品列表: {
    //   商品id: {
    //     商品图片
    //     商品价格
    //     商品原价
    //     数量
    //   }
    // }
    // }
    // { shopId: {shopName:'', productList:{ productId: {} }}}
    cartList: getLocalCartList(),
  },
  getters: {},
  mutations: {
    changeCartItemInfo(state, payload) {
      const { shopId, productId, productInfo, num } = payload;
      //如果shopInfo不存在 则置为空
      let shopInfo = state.cartList[shopId] || {
        shopName: '',
        productList: {},
      };

      let product = shopInfo.productList[productId];
      if (!product) {
        //如果商品不存在，则赋值为传入进来的商品 并且数量为0
        productInfo.count = 0;
        product = productInfo;
      }
      product.count += num; //如果存在,则+-对应数量
      product.count < 0 && (product.count = 0); //防止数量为负数
      num > 0 && (product.check = true); //往购物车中加商品 选中状态

      //最后两步再把值赋回给state
      shopInfo.productList[productId] = product;
      state.cartList[shopId] = shopInfo;
      setLocalCartList(state); //持久化存储
    },
    changeCartItemChecked(state, payload) {
      const { shopId, productId } = payload;
      const product = state.cartList[shopId].productList[productId];
      product.check = !product.check;
      setLocalCartList(state); //持久化存储
    },
    clearCartProducts(state, payload) {
      const { shopId } = payload;
      state.cartList[shopId].productList = {};
      setLocalCartList(state); //持久化存储
    },
    setCartItemChecked(state, payload) {
      const { shopId } = payload;
      const products = state.cartList[shopId].productList;
      if (products) {
        for (let item in products) {
          const product = products[item];
          product.check = true;
        }
      }
      setLocalCartList(state); //持久化存储
    },
    changeShopName(state, payload) {
      const { shopId, shopName } = payload;
      const shopInfo = state.cartList[shopId] || {
        shopName: '',
        productList: {},
      };
      shopInfo.shopName = shopName;
      state.cartList[shopId] = shopInfo;
      setLocalCartList(state); //持久化存储
    },
    clearCartData(state, payload) {
      // 清空购物车
      console.log('清空购物车: ');
      const { shopId } = payload;
      // state.cartList[shopId].productList = {};
      delete state.cartList[shopId];

      setLocalCartList(state); //持久化存储
    },
  },
  actions: {},
  modules: {},
});
